<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '推荐给好友',
  },
}
</route>

<template>
  <view class="py-32rpx bg-#fff"
    :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
  >
    <view class="w-center m-a rounded-16rpx bg-linear-5 h-358rpx box-border p-32rpx relative">
      <view class="font-size-32rpx color-#fff relative">
        账户乐缘币
        <i class="iconfont icon-qrcode !font-size-45rpx color-#fff position-c-center right-0"
          @click="getQrCode"
        ></i>
      </view>
      <view class="font-size-64rpx color-#fff font-500">{{ balance || 0 }}</view>
      <view class="w-full flex-sb-center absolute left-0 bottom-30rpx px-32rpx box-border">
        <view class="w-244rpx h-64rpx flex-center leading-0 box-border w-border rounded-64rpx color-#fff"
          @click="withdrawalCommissionConfirm"
        >提现</view>
        <view class="w-244rpx h-64rpx flex-center leading-0 rounded-64rpx color-#fff bg-linear-6 relative">
          <wd-button custom-class="share-btn" open-type="share">分享</wd-button>
          邀请好友
        </view>
      </view>
    </view>

    <view class="color-#9C6DEF font-size-32rpx mt-50rpx box-border px-32rpx">邀请记录</view>
    <view class="w-center m-a flex-sb-center !mt-18rpx !mb-12rpx">
      <view 
        class="w-1/2 h-46rpx font-size-24rpx rounded-8rpx flex-center color-#C8A2F9" 
        v-for="item in [{ label: '我的直推', value: 1 },{ label: '我的间推', value: 2 }]"
        :class="[activeValue === item.value ? 'bg-#C8A2F9 color-#fff' : '']"
        @click="handleChange(item)"
      >
        {{ item.label }}
      </view>
    </view>
    <view class="w-center m-a !mt-20rpx bg-#FAF7FF rounded-8rpx box-border p-32rpx"
      :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
    >
      <view class="flex-sb-center font-size-24rpx color-#986DF0 mb-10rpx">
        <view class="flex-1 text-center">code</view> 
        <view class="flex-1 text-center">消费金额</view> 
        <view class="flex-1 text-center">日期</view> 
        <view class="flex-1 text-center">分佣</view> 
      </view>
      <view class="flex-sb-center font-size-22rpx color-#979797"
        v-for="(item, index) in getInviteArr"
        :key="item.id"
        :class="[{ 'mb-16rpx': index !== getInviteArr.length - 1 }]"
      >
        <view class="flex-1 text-center ellipsis">{{ item.userCode }}</view> 
        <view class="flex-1 text-center ellipsis">{{ item.amount }}</view> 
        <view class="flex-1 text-center ellipsis">{{ formatDate(new Date(item.createTime), 'YYYY-MM-DD') || '--' }}</view> 
        <view class="flex-1 text-center ellipsis">{{ item.commissionAmount }}</view> 
      </view>
      <view class="w-full h-96rpx flex-center font-size-24rpx color-#986DF0" 
        v-if="!getInviteArr.length"
      >暂无记录</view>
    </view>

    <view class="color-#9C6DEF font-size-32rpx mt-50rpx box-border px-32rpx">提现记录</view>
    <view class="w-center m-a !mt-20rpx bg-#FAF7FF rounded-8rpx box-border p-32rpx"
      :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
    >
      <view class="flex-sb-center font-size-24rpx color-#986DF0"
        v-for="(item, index) in commissionWithdrawalHistory"
        :key="item.id"
        :class="[{ 'mb-16rpx': index !== commissionWithdrawalHistory.length - 1 }]"
      >
        <view class="">{{ item.withdrawalAmount || '--' }}乐缘币</view>
        <view class="">{{ formatDate(new Date(item.withdrawalDate)) || '--' }}</view>
      </view>
      <view class="w-full h-96rpx flex-center font-size-24rpx color-#986DF0" 
        v-if="!commissionWithdrawalHistory.length"
      >暂无记录</view>
    </view>
  </view>

  <wd-overlay :show="showOverlay" @click="showOverlay = false">
    <view class="w-464rpx bg-#fff position-center rounded-24rpx" @click.stop="downloadQrCode">
      <view class="w-200px h-200px m-a !mt-32rpx bg-#f1f1f1 rounded-24rpx font-size-0 relative">
        <canvas v-show="!isShowConfirm && !qrLoading" id="qrcode" canvas-id="qrcode" style="width: 200px;height: 200px;position: absolute;"></canvas>
        <canvas v-show="!isShowConfirm && !qrLoading" id="qrcodeCanvas" canvas-id="qrcodeCanvas" style="width: 200px;height: 220px;"></canvas>
        <view class="position-center" v-if="qrLoading">
          <wd-loading />
        </view>
      </view>
      <view class="color-#999 font-size-24rpx text-center pb-32rpx pt-54rpx">
        点击二维码下载推荐给好友
      </view>
    </view>
  </wd-overlay>
</template>
  
<script lang="ts" setup>
import UQRCode from 'uqrcodejs';
import { useThemeStore, useUserStore } from "@/store";
import { formatDate } from '../utils/index';
import { share } from "@/enum";
import { 
  CancelWithdrawToWeChat,
  GetInviteDetail,
  GetInviteList, 
  GetUserCommissionBalance, 
  GetUserCommissionWithdrawalHistory, 
  WithdrawMoneyToWeChat
} from "@/service/db_feature";
import { useMessage, useToast } from "wot-design-uni";

// 主题颜色
const { themeConfig } = useThemeStore();
const user = useUserStore();

const activeValue = ref(1);
const handleChange = (item) => {
  activeValue.value = item.value;
}

// 提现列表
const commissionWithdrawalHistory = ref([]);
const getUserCommissionWithdrawalHistory = async () => {
  try {
    const res = await GetUserCommissionWithdrawalHistory({
      userId: user.userInfo.id
    });
    commissionWithdrawalHistory.value = res.data || [];
  } catch (error) {
    console.log(error)
  }
}

// 邀请列表
const inviteList = ref([]);
const getInviteList = async () => {
  try {
    const res = await GetInviteList({
      introUserId: user.userInfo.id
    });
    inviteList.value = res.data || [];
  } catch (error) {
    console.log(error)
  }
}

const inviteDetail = ref({} as any);
// 获取邀请明细
const getInviteDetail = async () => {
  try {
    const res: any = await GetInviteDetail({
      rootCode: user.userInfo.code
    });
    inviteDetail.value = res || {};
  } catch (error) {
    console.log(error)
  }
}

// 邀请明细
const getInviteArr = computed(() => {
  const arr = ['ztInviteCommissionDetailList', 'jtInviteCommissionDetailList']
  const i = activeValue.value - 1;
  return inviteDetail.value[arr[i]] || [];
})

// 乐缘币
const balance = ref(0);
// 获取用户回佣乐缘币
const getUserCommissionBalance = async (isSetBalance = true) => {
  try {
    const res = await GetUserCommissionBalance({
      userId: user.userInfo.id
    });
    const data = res.data || {};
    isSetBalance && (balance.value = data.currentBalance || 0);

    getUserCommissionWithdrawalHistory();
    // getInviteList();
    getInviteDetail();
  } catch (error) {
    console.log(error)
  }
}

const message = useMessage();
const withdrawalCommissionConfirm = () => {
  message.prompt({
    title: '请输入乐缘币数量',
    inputValue: balance.value,
    inputError: '乐缘币余额不足',
    inputValidate: (val: number) => {
      return val <= balance.value;
    }
  }).then((data) => {
    withdrawalCommission(data.value);
  })
}

const toast = useToast();
const loading = ref(false);
// 提现
const withdrawalCommission = async (amount) => {
  try {
    if (loading.value) return;
    loading.value = true;
    const res = await WithdrawMoneyToWeChat({
      userId: user.userInfo.id,
      amount
    });
    loading.value = false;
    merchantTransfer(res.data, amount);
  } catch (error) {
    loading.value = false;
    console.log(error)
  }
}

/** 调起用户确认收款 */
const merchantTransfer = (data = {} as any, amount) => {
  if (wx.canIUse('requestMerchantTransfer')) {
    uni.showLoading({
      title:'正在调起提现窗口...',
    })
    wx.requestMerchantTransfer({
      mchId: '1695613612',
      appId: wx.getAccountInfoSync().miniProgram.appId,
      package: data.package_info,
      success: (res) => {
        wx.hideLoading();
        // res.err_msg将在页面展示成功后返回应用时返回ok，并不代表付款成功
        if (res.result === 'success') {
          toast.show('提现成功!');
          // cancelWithdrawToWeChat(data.commissionWithdrawId, 'COMPLETED');
          balance.value = Number((balance.value - Number(amount)).toFixed(1));
          getUserCommissionBalance(false);
        } else {
          // 取消提现
          cancelWithdrawToWeChat(data.commissionWithdrawId, 'CANCEL');
        }
      },
      fail: (res) => {
        wx.hideLoading();
        // 取消提现
        cancelWithdrawToWeChat(data.commissionWithdrawId, 'CANCEL');
        console.log('fail:', res);
      },
    });
  } else {
    wx.showModal({
      content: '你的微信版本过低，请更新至最新版本。',
      showCancel: false,
    });
  }
}

// 取消提现
const cancelWithdrawToWeChat = async(id, status) => {
  try {
    const res = await CancelWithdrawToWeChat({ id, status });
    getUserCommissionBalance();
  } catch (error) {
    console.log(error)
  }
}

const showOverlay = ref(false);
const qrLoading = ref(false)
const getQrCode = () => {
  showOverlay.value = true;
  setTimeout(() => {
    try {
      qrLoading.value = true;
      const id = user.userInfo.id || '';
      // 获取uQRCode实例
      let qr = new UQRCode();
      // 设置二维码内容
      qr.data = "https://h5.fytxcq.cn/#/pages/tabbar/index?instrId=" + id;
      // 设置二维码大小，必须与canvas设置的宽高一致
      qr.size = 200;
      qr.margin = 6;
      // 调用制作二维码方法
      qr.make();
      // 获取canvas上下文
      let canvasContext = uni.createCanvasContext('qrcode', this); // 如果是组件，this必须传入
      // 设置uQRCode实例的canvas上下文
      qr.canvasContext = canvasContext;
      // 调用绘制方法将二维码图案绘制到canvas上
      qr.drawCanvas();
      
      
      // #ifdef H5
      getQrcodeImage();
      // #endif
      
      // #ifdef MP-WEIXIN
      setTimeout(() => {
        getQrcodeImage();
      }, 300)
      // #endif
    } catch (error) {
      qrLoading.value = false;
    }
  }, 300)
}

// 获取qrcode图片
const getQrcodeImage = () => {
  // 获取临时文件路径
  uni.canvasToTempFilePath({
    canvasId: 'qrcode',
    fileType: 'png',
    width: 200,
    height: 200,
    success: res => {
      drawCanvas(res.tempFilePath);
    },
  });
}

// 绘制二维码和文字
const drawCanvas = async (tempFilePath) => {
  const ctx = uni.createCanvasContext('qrcodeCanvas');
  const canvasWidth = 200;
  const canvasHeight = 220;
  
  // 绘制白色背景
  ctx.setFillStyle('#ffffff');
  ctx.fillRect(0, 0, canvasWidth, canvasHeight);
  
  // 绘制二维码
  ctx.drawImage(tempFilePath, 0, 0, 200, 200);
  
  // 绘制文字
  ctx.setFontSize(16);
  ctx.setFillStyle('#986DF0');
  ctx.setTextAlign('center');
  ctx.fillText('丹身乐缘婚恋网', canvasWidth/2, 214);
  
  ctx.draw();
  qrLoading.value = false;
}

// 下载二维码
const downloadQrCode = () => {
  // 获取临时文件路径
  uni.canvasToTempFilePath({
    canvasId: 'qrcodeCanvas',
    fileType: 'png',
    width: 200,
    height: 220,
    success: res => {
      // h5下载
      // #ifdef H5
      const aEle = document.createElement('a');
      aEle.download = 'uQRCode'; // 设置下载的文件名，默认是'下载'
      aEle.href = res.tempFilePath;
      document.body.appendChild(aEle);
      aEle.click();
      aEle.remove(); // 下载之后把创建的元素删除
      // #endif

      // 微信保存到相册
      // #ifdef MP-WEIXIN
      uni.authorize({
        scope: 'scope.writePhotosAlbum',
        success() {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: res => {},
          });
        },
        fail:(fail)=>{
          toSetting();
        },
      })
      // #endif
    },
  });
}

const isShowConfirm = ref(false);
// 去授权
const toSetting = () => {
  isShowConfirm.value = true;
  message
    .confirm({
      msg: `保存二维码需要授权添加到相册`,
      title: '提示',
      confirmButtonText: '去授权'
    })
    .then(() => {
      uni.openSetting({
        success: res => {
          isShowConfirm.value = false;
          console.log('打开设置成功', res)
        },
        fail:(fail)=>{
          isShowConfirm.value = false;
          console.log('打开设置失败', fail)
        },
      })
    })
    .catch(() => {
      isShowConfirm.value = false;
      console.log('点击了取消按钮')
    })
}

onShow(() => {
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = '推荐给好友';
  })
})

onLoad(() => {
  getUserCommissionBalance();
})

onShareAppMessage(() => {
  const { id = '', userProfileInfoVo } = user.userInfo || {};
  const { partnerRequirements, personalImageryInfoVoList = [] } = userProfileInfoVo || {};
  const firstItem = personalImageryInfoVoList[0] || { fileInfoVo: { preUrl: '' } };
  const _fileInfoVo = firstItem.fileInfoVo || { preUrl: '' };
  
  return {
    title: '我满心期待，与你相遇的未来！',
    path: `/pages/tabbar/index?instrId=${id || ''}`,
    imageUrl: share
  }
})
</script>

<style lang="scss" scoped>
.w-border {
  border: 1px solid #fff;
}
</style>
        